package com.raycloud.robot.custom.zdfUtils;

import java.util.concurrent.TimeUnit;
import org.apache.http.impl.client.HttpClientBuilder;
import java.security.NoSuchAlgorithmException;
import java.io.InterruptedIOException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import java.net.SocketTimeoutException;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.util.EntityUtils;
import com.raycloud.robot.custom.zdfUtils.exception.ZdfServiceException;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import java.security.MessageDigest;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.jboss.netty.util.CharsetUtil;
import com.alibaba.fastjson.JSON;
import java.util.Map;
import org.springframework.util.CollectionUtils;
import org.apache.http.client.methods.HttpPost;
import org.springframework.util.StringUtils;
import org.springframework.util.Assert;
import java.util.Objects;
import com.raycloud.robot.custom.zdfUtils.dto.basic.BasicZdfResponse;
import com.raycloud.robot.custom.zdfUtils.dto.basic.BaseZdfRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.client.config.RequestConfig;

public class ZdfPictureUtils{
    private static String HOST;
    private static String ZDF_KEY_TEST;
    private static String ZDF_SECRET_TEST;
    private static String ZDF_KEY;
    private static String ZDF_SECRET;
    private static RequestConfig requestConfig;
    private static final CloseableHttpClient client;
    private static final int HTTPCODE_OK=200;
    public static <T extends BasicZdfResponse> T sendMsgInfo(final BaseZdfRequest<T> request) throws NoSuchAlgorithmException,ZdfServiceException{
        Assert.isTrue(Objects.nonNull(request),"request object is null");
        Assert.isTrue(!StringUtils.isEmpty(request.getHttpPath()),"request path is null");
        final HttpPost post=new HttpPost(ZdfPictureUtils.HOST+request.getHttpPath());
        try{
            try{
                final Map<String,Object> params=request.getParams();
                String paramStr="";
                if(!CollectionUtils.isEmpty(params)){
                    paramStr=JSON.toJSONString(params);
                    final ByteArrayEntity byteArrayEntity=new ByteArrayEntity(paramStr.getBytes(CharsetUtil.UTF_8),ContentType.APPLICATION_JSON);
                    post.setEntity((HttpEntity)byteArrayEntity);
                }
                final long current=System.currentTimeMillis();
                final String secret=paramStr+current+ZdfPictureUtils.ZDF_SECRET;
                final MessageDigest sha1=MessageDigest.getInstance("SHA1");
                final byte[] result=sha1.digest(secret.getBytes(CharsetUtil.UTF_8));
                final StringBuffer secretStr=new StringBuffer();
                for(int i=0;i<result.length;++i){
                    secretStr.append(Integer.toString((result[i]&0xFF)+256,16).substring(1));
                }
                post.setHeader((Header)new BasicHeader("Aibee-Auth-ApiKey",ZdfPictureUtils.ZDF_KEY));
                post.setHeader("Aibee-Auth-Sign",secretStr.toString());
                post.setHeader((Header)new BasicHeader("Aibee-Auth-Timestamp",String.valueOf(current)));
                final CloseableHttpResponse execute=ZdfPictureUtils.client.execute((HttpUriRequest)post);
                if(Objects.isNull(execute.getStatusLine())||!Objects.equals(200,execute.getStatusLine().getStatusCode())){
                    throw new ZdfServiceException("\u5468\u5927\u798f\u4ee5\u56fe\u641c\u56fe\u6570\u636e \u8bf7\u6c42\u5931\u8d25 http code \u4e0d\u7b49\u4e8e 200");
                }
                final String resp=EntityUtils.toString(execute.getEntity(),CharsetUtil.UTF_8);
                if(StringUtils.isEmpty(resp)){
                    return (T)new BasicZdfResponse.EmptyResp(-1,"no data","nothing");
                }
                final JSONObject jsonObject=JSON.parseObject(resp);
                final JSONObject data=jsonObject.getJSONObject("data");
                T resultT=null;
                if(Objects.nonNull(data)){
                    resultT=data.toJavaObject(request.getResponseClass());
                    resultT.setRequestId(jsonObject.getString("request_id"));
                    resultT.setErrorMsg(jsonObject.getString("error_msg"));
                    resultT.setErrorNo(jsonObject.getInteger("error_no"));
                }
                else{
                    resultT=jsonObject.toJavaObject(request.getResponseClass());
                }
                return resultT;
            }
            catch(ZdfServiceException e){
                throw e;
            }
            catch(ConnectTimeoutException exception){
                throw new ZdfServiceException("\u8bf7\u6c42\u5468\u5927\u798f\u4ee5\u56fe\u641c\u56fe\u6570\u636e\u51fa\u73b0\u8d85\u65f6",exception);
            }
            catch(Exception e2){
                throw new ZdfServiceException("\u8bf7\u6c42\u5468\u5927\u798f\u4ee5\u56fe\u641c\u56fe\u6570\u636e\u51fa\u73b0\u5f02\u5e38",e2);
            }
        }
        catch(SocketTimeoutException ex){
        }
    }
    static{
        ZdfPictureUtils.HOST="http://120.25.159.131:80";
        ZdfPictureUtils.ZDF_KEY_TEST="CTFTestNe3XyaDSGWzkP120teh5rfIipMg";
        ZdfPictureUtils.ZDF_SECRET_TEST="CTFTest6xz2hfoBAT7t1md3awg17xpOI5";
        ZdfPictureUtils.ZDF_KEY="CTFAccountNe3XyaDSGWzkP120teh5rfIipMg";
        ZdfPictureUtils.ZDF_SECRET="CTFSecret6xz2hfoBAT7t1md3awg17xpOI5";
        ZdfPictureUtils.requestConfig=RequestConfig.custom().setConnectionRequestTimeout(2000).setConnectTimeout(2000).setSocketTimeout(2000).build();
        client=HttpClientBuilder.create().setDefaultRequestConfig(ZdfPictureUtils.requestConfig).setMaxConnPerRoute(100).setMaxConnTotal(100).setConnectionTimeToLive(3L,TimeUnit.SECONDS).build();
    }
}
